package vt.ece4564.phonetracker;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


/**
 * @author BMW
 *
 */
public class Settings extends Activity implements OnClickListener {

	private EditText secretPhrase_;
	private Button save_;
	private Button advance_;
	public static final String phraseFile = "PhoneTrackerPrefsFile";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        
        secretPhrase_ = (EditText) findViewById(R.id.secretPhrase);
		save_ = (Button) findViewById(R.id.save);
		advance_ = (Button) findViewById(R.id.advanced);
		
		save_.setOnClickListener(this);
		advance_.setOnClickListener(this);
		// Restore preferences
		SharedPreferences settings = getSharedPreferences(phraseFile, 0);
		String phrase = settings.getString("Phrase", "");
		secretPhrase_.setText(phrase);
    }
    
    protected void onStop(){
		super.onStop();
		
		System.out.println("called onStop()");

		// We need an Editor object to make preference changes.
		// All objects are from android.context.Context
		SharedPreferences settings = getSharedPreferences(phraseFile, 0);
		String phrase = settings.getString("Phrase", "");
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("Phrase", phrase);
		editor.putString("secretphrase", phrase);

		// Commit the edits!
		editor.commit();
		
		// Commit valid secret phrase to screen
		secretPhrase_.setText(phrase);
	}

   /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_settings, menu);
        return true;
    }*/

	@Override
	public void onClick(View v) {
		//String phrase = secretPhrase_.getText().toString(); 
		SharedPreferences settings = getSharedPreferences(phraseFile, 0);
		Toast tag;
		
		//Switch statement to pick correct onClickListener
		switch(v.getId()) {
        case R.id.save: // Save secret phrase
        	SharedPreferences.Editor editor = settings.edit();
        	editor.putString("Phrase", secretPhrase_.getText().toString());
        	editor.putString("secrethrase", secretPhrase_.getText().toString());
        	secretPhrase_.getText().toString();
        	editor.commit();
        	tag = Toast.makeText(this, "Secret Phrase Saved", Toast.LENGTH_LONG);
    		tag.show();
			stopService(new Intent(Settings.this,PhoneFinderService.class));
			Intent serviceIntent = new Intent(Settings.this,PhoneFinderService.class);
			startService(serviceIntent);
        	break;
        case R.id.advanced: // Launch Child Finder
        	Intent i = new Intent(Settings.this,ChildFinderLogin.class);
			startActivity(i);
			break;
		}
	}
}
